#include "logger.h"

qLogger::qLogger(std::string& filename)
{
  logger_ = log4cxx::Logger::getLogger(filename);
  log4cxx::Logger::getRootLogger()->setLevel(log4cxx::Level::getDebug());

  local_logname_ = filename;
  addLocalFileLog(local_logname_);
  //addConsoleLog();

  bzero(message_, sizeof(message_));
}

qLogger::~qLogger()
{

}

void qLogger::setName(const std::string& name)
{
  logger_ = log4cxx::Logger::getLogger(name);
  if(!local_logname_.empty())
    addLocalFileLog(local_logname_);
}

const char CONSOLE[] = "console";
void qLogger::addConsoleLog()
{
  log4cxx::LoggerPtr root = log4cxx::Logger::getRootLogger();
  if(root->getAppender(CONSOLE))
    return;

  log4cxx::PatternLayoutPtr pl = new log4cxx::PatternLayout("%d{yyyy MMM dd HH:mm:ss}%c %p: %m%n");
  log4cxx::ConsoleAppenderPtr cap = new log4cxx::ConsoleAppender(pl);
  cap->setName(CONSOLE);
  root->addAppender(cap);
}

void qLogger::removeConsoleLog()
{
  log4cxx::Logger::getRootLogger()->removeAppender(CONSOLE);
}
    
void qLogger::addLocalFileLog(const std::string& file)
{
  size_t pos = file.rfind("/");
  if(pos != std::string::npos)
  {
    //文件路径
    std::string strPath = file.substr(0, pos + 1);
    //判断文件路径是否存在
    if(access(strPath.c_str(), F_OK) != 0)
    {
      //创建目录
      if(mkdir(strPath.c_str(), 0776) == -1)
      {
        error("create %s fail FFL[%s, %s, %d]", strPath.c_str(), LOG_FFL);
      }
    }
  }

  log4cxx::PatternLayoutPtr pl = new log4cxx::PatternLayout("%d{yyyy MMM dd HH:mm::ss,SSS} %c %p: %m%n");
  log4cxx::DailyRollingFileAppender* drfa = new log4cxx::DailyRollingFileAppender(pl, file, ".yyyy-MM-dd-HH-mm");
  drfa->setName("localfle"+file);
  logger_->addAppender(drfa);

}

    
void qLogger::removeLocalFileLog(const std::string& file)
{
  log4cxx::AppenderPtr ap = logger_->getAppender("localfile" + file);
  logger_->removeAppender(ap);
  ap->close();
}

//void qLogger::getMessage(const char* pattern)
//{
//  bzero(message_, MSG_LEN);
//  va_list ap;
//  vsnprintf(message_, MSG_LEN - 1, pattern, ap);
//  va_end(ap);
//}

#define getMessage(msg, msglen, pattern) \
do {\
  bzero(msg, msglen); \
  va_list ap; \
  va_start(ap, pattern); \
  vsnprintf(msg, msglen - 1, pattern, ap); \
  va_end(ap); \
}while(false);

void qLogger::info(const char* pattern, ...)
{
  mt_.lock();
  getMessage(message_, MSG_LEN, pattern);  

  logger_->info(message_);

  mt_.unlock();
}

void qLogger::log(const char* pattern, ...)
{

}

void qLogger::debug(const char* pattern, ...)
{
  mt_.lock();
  getMessage(message_, MSG_LEN, pattern);

  logger_->debug(message_);

  mt_.unlock();
}

void qLogger::warn(const char* pattern, ...)
{
  mt_.lock();
  getMessage(message_, MSG_LEN, pattern);

  logger_->warn(message_);

  mt_.unlock();

}
    
void qLogger::error(const char* pattern, ...)
{
  mt_.lock();
  getMessage(message_, MSG_LEN, pattern);

  logger_->error(message_);

  mt_.unlock();

}
